﻿using System.Collections.Generic;

namespace System.Web.Mvc
{

    public static class EnumDropDownList
    {

        /// <summary>
        /// Creates a dropdown list from an enum
        /// </summary>        
        /// <param name="name">name of the element</param>
        /// <param name="type">the enum type</param>
        /// <returns></returns>
        public static MvcHtmlString DropDownList(this HtmlHelper helper, string name, Type type)
        {
            return DropDownList(helper, name, type, null);
        }

        /// <summary>
        /// Creates a dropdown list from an enum.
        /// </summary>        
        /// <param name="name">name of an element</param>
        /// <param name="type">the enum type</param>
        /// <param name="selected">selected enum value</param>
        /// <returns></returns>
        public static MvcHtmlString DropDownList(this HtmlHelper helper, string name, Type type, object selected)
        {
            if (!type.IsEnum)
                throw new ArgumentException("Type is not an enum.");

            if (selected != null && selected.GetType() != type)
                throw new ArgumentException("Selected object is not " + type);

            var enums = new List<SelectListItem>();
            foreach (int value in Enum.GetValues(type))
            {
                var item = new SelectListItem();
                item.Value = value.ToString();
                item.Text = Enum.GetName(type, value).Replace("_"," ");

                if (selected != null)
                    item.Selected = (int)selected == value;

                enums.Add(item);
            }

            return Html.SelectExtensions.DropDownList(helper, name, enums);
        }

    }
    
}
